package eyrolles;

import exceptions.LoginException;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.ActionMessage;

import java.sql.SQLException;

public class LoginAction extends ActionDB {

    protected String getUser(String username, String password) throws SQLException, LoginException {

        String user = null;

        try {

            conn = getConnection();
            stmt = conn.createStatement();
            rs = stmt.executeQuery("select * from employes where username=\'"
                    + username + "' "
                    + "and password='" + password + "'");

            if (rs.next()) {

                user = rs.getString("username");

            } else {
                throw new LoginException();
            }
        } catch (NullPointerException n) {

            throw new SQLException();
            
        } finally {

            closeConnection();
        }
        return user;
    }

    public ActionForward execute(ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response)
            throws IOException, ServletException {

        ActionMessages errors = new ActionMessages();
        String user = null;

        // Cible par defaut en cas de succes
        String target = new String("success");

        // Action errors
        errors = new ActionMessages();

        // Utilisation de LoginForm pour obtenir les parametres
        // de la requete
        String username = ((LoginForm) form).getUsername();
        String password = ((LoginForm) form).getPassword();

        try {
            user = getUser(username, password);
            HttpSession session = request.getSession();
            session.setAttribute("USER", user);
        } catch (SQLException e) {

            errors.add(ActionMessages.GLOBAL_MESSAGE,
                    new ActionMessage("errors.database.error", username));
            target = new String("login");


        } catch (LoginException l) {


            errors.add(ActionMessages.GLOBAL_MESSAGE,
                    new ActionMessage("errors.login.unknown", username));
            target = new String("login");
        }

        // Enregistrer les erreurs  trouvees dans le formulaire original
        if (!errors.isEmpty()) {

            saveErrors(request, errors);
        } 

        // Transmission de la requete a la vue appropriee
        return (mapping.findForward(target));
    }
}
